<script lang="ts" setup>
import { shallowRef } from 'vue'
import { gsap } from 'gsap'

withDefaults(
  defineProps<{
    items: {
      title: string
      items: string[]
    }[]
  }>(),
  {
    items: () => [],
  },
)

const activatedContent = shallowRef<Element | null>(null)
const activatedTitle = shallowRef<Element | null>(null)
const fold = (event: Event) => {
  if (activatedContent.value) {
    activatedContent.value.classList.remove('active')
  }

  const btn = event.currentTarget as HTMLDivElement
  if (!btn) {
    return
  }
  const container = btn.parentNode
  if (!container) {
    return
  }
  const content = container.querySelector('.fold-content')
  if (!content) {
    return
  }

  const line2 = btn.querySelector('.line2')
  if (content === activatedContent.value) {
    activatedContent.value = null
    if (line2) {
      gsap.to(line2, {
        autoAlpha: 1,
        duration: 0.3,
      })
    }
  } else {
    content?.classList.add('active')
    activatedContent.value = content

    if (activatedTitle.value) {
      gsap.to(activatedTitle.value, {
        autoAlpha: 1,
        duration: 0.3,
      })
    }
    if (line2) {
      activatedTitle.value = line2
      gsap.to(line2, {
        autoAlpha: 0,
        duration: 0.3,
      })
    }
  }
}
</script>

<template>
  <ul>
    <li
      v-for="(item, key) in items"
      :key
      class="py-[1rem] px-[clamp(1rem,0.3639rem+2.3669vw,1.5rem)] cursor-pointer"
    >
      <div class="flex items-center justify-between" @click="fold">
        <p>{{ item.title }}</p>
        <div class="px-[0.375rem]">
          <div class="w-[0.875rem] h-[2px] bg-[#0000008c] translate-y-full"></div>
          <div
            class="line2 w-[0.875rem] h-[2px] bg-[#0000008c]"
            style="transform-origin: center; transform: rotate(90deg)"
          ></div>
        </div>
      </div>

      <div class="fold-content">
        <div class="grid-item">
          <ul class="mt-[0.375rem]">
            <li
              v-for="i in item.items"
              :key="i"
              class="pl-[0.75rem] py-[0.5rem] flex justify-between items-center text-[#0000008c] cursor-pointer hover:text-[#000000f2]"
            >
              <p>{{ i }}</p>
              <svg class="opacity-55" height="24" width="24">
                <use href="#icon-com-arrow-right" />
              </svg>
            </li>
          </ul>
        </div>
      </div>
    </li>
  </ul>
</template>

<style scoped>
.fold-content.active {
  grid-template-rows: 1fr;
}

.fold-content {
  display: grid;
  grid-template-rows: 0fr;
  transition: all 0.3s;

  .grid-item {
    min-height: 0;
    overflow: hidden;
  }
}
</style>
